`timescale 1ns / 100ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date: 2024/01/24 19:40:00
// Design Name: 
// Module Name: tb_top_histogram
// Project Name: 
// Target Devices: 
// Tool Versions: 
// Description: 
// 
// Dependencies: 
// 
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// 
//////////////////////////////////////////////////////////////////////////////////


module tb_top_histogram();

integer file_hist; 
integer file_gray;
initial begin
    file_gray=$fopen("./image_gray.txt","r");
    file_hist=$fopen("./histogram.txt","w");
end

reg clk=1'b0;
always #1 clk=~clk;

reg rst_n=1'b0;
initial begin
    #2;
    rst_n<=1'b1;
end

reg pin_clken;
reg [7:0] gray;
wire [7:0] gray_hist;
wire pout_clken;
wire wen;

reg [1:0] i=2'd0;
always @(posedge clk or negedge rst_n) begin
    if(!rst_n) begin
        gray<=8'd0;
        pin_clken<=1'b0;
    end
    else begin
        case (i)
            2'd0:begin
                $fscanf(file_gray,"%d\n",gray);
                i<=i+1;
                pin_clken<=1'b0;
            end
            2'd1:begin
                if(!wen)begin
                    pin_clken<=1'b1;
                    i<=2'd0;
                end
            end
            default:begin
                i<=2'd0;
                pin_clken<=1'b0;
            end
        endcase
    end
end


top_histogram u_top_histogram(
    .clk(clk),
    .rst_n(rst_n),

    .gray(gray),
    .pin_clken(pin_clken),

    .wen(wen),
    .hist_gray(gray_hist),
    .pout_clken(pout_clken)

);

parameter image_width=512;
parameter image_height=512;
parameter total_pixels=image_width*image_height;
integer j=0;
always @(posedge clk) begin
        if(pout_clken)begin
            $fwrite(file_hist,"%d\n",gray_hist);
            j=j+1;
        end
end
always @(posedge clk) begin
        if(j==total_pixels)begin
            $fclose(file_hist);
            $fclose(file_gray);
            $stop;
        end
end
endmodule